package leo.mystudy.sorts;

import leo.mystudy.utils.ArrayUtil;

/**
 * @author lichao email:lichao@witspring.com
 * @Description: 快速排序
 * @Date 2018/4/23 16:39
 * @since Ver V0.0.1
 */
public class QuickSort {

    public static void main(String[] args) {
        Integer[] array = new Integer[]{1, 4, 2, 5, 7, 3};
        array = QuickSort.sort(array);
        for (int i : array) {
            System.out.println(i);
        }
    }

    public static Integer[] sort(Integer[] array) {
        if (array == null || array.length <= 1) {
            return array;
        }
        qSort(array, 0, array.length - 1);
        return array;
    }

    private static void qSort(Integer[] array, int low, int high) {
        int pivot;
        if (low < high) {
            pivot = partition(array, low, high);
            qSort(array, low, pivot - 1);
            qSort(array, pivot + 1, high);
        }
    }

    /**
     * 交换array中的顺序，使枢轴记录到位，并返回轴枢的位置
     *
     * @param array
     * @param low
     * @param high
     * @return 轴枢位置
     */
    private static int partition(Integer[] array, int low, int high) {
        int pivotKey = array[low];
        while (low < high) {
            while (low < high && array[high] >= pivotKey) {
                high--;
            }
            ArrayUtil.swap(array, low, high);
            while (low < high && array[low] <= pivotKey) {
                low++;
            }
            ArrayUtil.swap(array, low, high);
        }
        return low;
    }

}
